from hashlib import sha1
from re import search
from urllib.request import Request, urlopen, HTTPError

HOSTSDIR = r'C:\Windows\System32\drivers\etc\hosts'
HOSTURL = r'https://raw.githubusercontent.com/racaljk/hosts/master/hosts'

def getDate(text):
    res = search(r'Last updated: ([0-9\-]+)', text)
    if res:
        return res.group(1)
    return False

def getGitSha1(text):
    return sha1(f'blob {len(text)}\0{text}'.encode('utf-8')).hexdigest()

with open(HOSTSDIR) as f: 
    oldFile = f.read()
date = getDate(oldFile)
oldHash = ''
if date:
    oldHash = getGitSha1(oldFile)
    print('本地版本:')
    print(f'{date} {oldHash}')
    req = Request(HOSTURL, headers={'If-None-Match': f'"{oldHash}"'})
else:
    print('本地版本未知')
    req = Request(HOSTURL)

try:
    res = urlopen(req)
    resText = res.read().decode('utf-8')
    resHash = res.getheader('ETag').strip('"')
    if oldHash != resHash:
        print('检测到最新版：')
        print(f'{getDate(resText)} {resHash}')
        with open(HOSTSDIR, 'w') as f:
            f.write(resText)
            print('已更新至最新版')
except HTTPError as err:
    if err.code == 304:
        print('已是最新版')
    else:
        print(f'请求失败，错误码{err.code}')

